<template>
  <div class="bg-white">
    <el-form :model="editForm" :rules="rules" ref="editFormRef">
      <BaseTable>
        <tr>
          <td class="td-name">组织形式</td>
          <td>
            <el-form-item label="" prop="formId" class="mb-[0px]">
              <CommonRadio
                :isFetch="false"
                :dataList="zzTypeList"
                v-model="editForm.formId"
                valueKey="code"
                @change="zzTypeChange"
              />
            </el-form-item>
          </td>
          <td class="td-name">
            <template v-if="editForm.formId == 2">
              牵头单位<span class="no-empty">*</span>
            </template>
          </td>
          <td>
            <el-form-item label="" prop="leadUnitName" class="mb-[0px]" v-if="editForm.formId == 2">
              <el-input v-model="editForm.leadUnitName" placeholder="" clearable />
            </el-form-item>
          </td>
        </tr>
        <tr>
          <td class="td-name">合作形式<span class="no-empty">*</span></td>
          <td colspan="3">
            <el-form-item label="" prop="cooperateId" class="mb-[0px]" style="width: 240px">
              <CommonSelect
                :isFetch="false"
                :dataList="hzTypeList"
                v-model="editForm.cooperateId"
                valueKey="code"
              />
            </el-form-item>
          </td>
        </tr>
      </BaseTable>
    </el-form>
  </div>
  <div class="bg-white my-[10px]">
    <BaseHead style="border-bottom: 0">
      合作单位 <el-button @click="handleAdd">添加</el-button></BaseHead
    >
    <el-table :data="unitList" class="w-full" border stripe>
      <el-table-column type="index" label="序号" width="60px" />
      <el-table-column label="单位名称">
        <template #default="{ row }">
          <div class="flex items-center">
            <span class="no-empty-icon">*</span>
            <el-input clearable v-model="row.unitName" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="负责人">
        <template #default="{ row }">
          <el-input v-model="row.chargerName" placeholder="" clearable />
        </template>
      </el-table-column>
      <el-table-column label="合同金额（万元）">
        <template #default="{ row }">
          <div class="flex items-center">
            <span class="no-empty-icon">*</span>
            <el-input
              v-model="row.contractFee"
              clearable
              @input="fomateNumber(row, 'contractFee', $event)"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="单位类型">
        <template #default="{ row }">
          <CommonSelect
            :isFetch="false"
            :dataList="unitTypeList"
            v-model="row.unitType"
            valueKey="code"
          />
        </template>
      </el-table-column>
      <el-table-column label="银行名称">
        <template #default="{ row }">
          <el-input v-model="row.bankName" placeholder="" clearable />
        </template>
      </el-table-column>
      <el-table-column label="银行账号">
        <template #default="{ row }">
          <el-input v-model="row.bankNum" placeholder="" clearable />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="100" align="center">
        <template #default="{ $index }">
          <el-button type="primary" size="small" plain @click="handleDel($index)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import BaseTable from "@/views/project/components/BaseTable.vue";
import CommonSelect from "@/views/project/components/CommonSelect.vue";
import CommonRadio from "@/views/project/components/CommonRadio.vue";
import { editUnit, unitDetail } from "@/api/project/zx/lxxm";
import { ElMessage } from "element-plus";
import { assignObj, fomateNumber } from "@/utils/main";
import { vilidCardCode } from "@/utils/validate";
const unitTypeList = inject("unitTypeList");
const zzTypeList = inject("zzTypeList");
const hzTypeList = inject("hzTypeList");
const baseData = ref({});
const unitList = ref([]);
const operateId = ref(null);
const editFormRef = ref();
const outFee = ref(0); //外拨经费
const isAuditor = inject("isAuditor");
const taskId = inject("taskId");
const checkStatus = inject("checkStatus");
const editForm = reactive({
  formId: "",
  leadUnitName: "",
  cooperateId: "",
});
const rules = {
  leadUnitName: [
    {
      required: true,
      message: "牵头单位必填",
    },
  ],
  cooperateId: [
    {
      required: true,
      message: "合作形式必填",
    },
  ],
};
//初始化一个单位 用于添加
const initUnitItem = () => {
  return {
    projectId: operateId.value,
    unitName: "",
    chargerName: "",
    contractFee: "",
    unitType: "",
    bankName: "",
    bankNum: "",
  };
};
//组织形式改变
const zzTypeChange = () => {
  editForm.leadUnitName = "";
};
//点击添加按钮
const handleAdd = () => {
  unitList.value.push(Object.assign({}, initUnitItem()));
};
//点击删除按钮删除一行
const handleDel = (index) => {
  unitList.value.splice(index, 1);
};
//获取单位信息详情
const getUnitDetail = async () => {
  try {
    const res = await unitDetail(operateId.value);
    baseData.value = res.data.proInitOtherBaseInfoVo;
    unitList.value = res.data.bizProjectCooperationUnitList;
    outFee.value = parseFloat(res.data.proInitOtherBaseInfoVo.outFee);
  } catch (error) {
    console.log(error);
  }
};
//编辑
const edit = async (id) => {
  operateId.value = id;
  //获取单位列表
  await getUnitDetail();
  assignObj(editForm, baseData.value);
};
const emit = defineEmits(["save-success", "save-ok"]);
//保存
const save = async (submitType) => {
  try {
    await editFormRef.value?.validate(async (valid) => {
      if (valid) {
        let total = 0;
        let nullFlag = false;
        let cardCodeFlag = false;
        unitList.value.forEach((item) => {
          total += item.contractFee ? parseFloat(item.contractFee) : 0;
          if (!item.unitName || !item.contractFee) {
            nullFlag = true;
          }
          if (item.bankNum && !vilidCardCode(item.bankNum)) {
            cardCodeFlag = true;
          }
        });
        //校验合作单位名称是否全部填写
        if (nullFlag) {
          ElMessage({
            message: "请检查各项必填字段是否全部填写！",
            type: "error",
          });
          return;
        }
        //校验银行卡号
        if (cardCodeFlag) {
          ElMessage({
            message: "银行账号格式不正确！",
            type: "error",
          });
          return;
        }
        //校验外拨经费和合同经费总和是否相等
        if (total != outFee.value) {
          ElMessage({
            message: "合作单位合同金额之和与外拨金额不相等！",
            type: "error",
          });
          return;
        }
        const params = {
          proId: operateId.value,
          submitType,
          isAuditor: isAuditor.value,
          taskId: taskId.value,
          checkstatus: checkStatus.value,
          ...editForm,
          cooperationUnits: unitList.value,
        };
        const res = await editUnit(params);
        if (res.code === 200) {
          emit("save-success");
        }
      }
    });
  } catch (error) {
    console.log(error);
  } finally {
    emit("save-ok");
  }
};
defineExpose({ edit, save });
</script>

<style scoped lang="scss">
@import url("@/views/project/index.scss");
.base-table {
  border-top: 0;
  tr {
    &:first-child {
      td {
        border-top: 0;
      }
    }
  }
}
</style>
